package org.mengyun.tcctransaction.sample.service;

import java.util.Optional;

import org.mengyun.tcctransaction.api.Compensable;
import org.mengyun.tcctransaction.sample.domain.dto.OrderDto;
import org.mengyun.tcctransaction.sample.domain.entity.TccOrder;
import org.mengyun.tcctransaction.sample.domain.repository.OrderRepository;
import org.mengyun.tcctransaction.sample.domain.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * xuejianxin
 */
@Service
public class OrderService {

	@Autowired
	OrderRepository orderRepository;

	@Autowired
	IProductService productServiceProxy;

	@Compensable(confirmMethod = "confirmCreateOrder", cancelMethod = "cancelCreateOrder", asyncConfirm = true)
	@Transactional
	public void tryCreateOrder(OrderDto od) {
		TccOrder o=createOrder(od);
		od.setId(o.getId());// 设置订单id
		// 没有必要传递事物上下文,第一个参数会在切面中注入,前提是必须通过代理类来调用
		//一定要遵守幂等性
		productServiceProxy.reduceStock(null, od);
		System.out.println("=====================tryCreateOrder:" + od);
		//int a = 1 / 0;
	}
	
	private TccOrder createOrder(OrderDto od) {
		TccOrder o = new TccOrder();
		o.setProductId(od.getProductId());
		o.setUserId(od.getUserId());
		o.setTccStatus("0");
		orderRepository.save(o);
		return o;
	}
	
	

	public void confirmCreateOrder(OrderDto od) {
		System.out.println("****************************==confirmCreateOrder:" + od);
		TccOrder o = orderRepository.findById(od.getId()).get();
		o.setTccStatus("1");
		orderRepository.save(o);
	}

	public void cancelCreateOrder(OrderDto od) {
		System.out.println("xxxxxxxxxxxxxxxxxxx====confirmCreateOrder:" + od);
		Optional<TccOrder> o = orderRepository.findById(od.getId());
		if (o.isPresent()) {
			orderRepository.deleteById(od.getId());
		}
	}

}
